/*
 *  IBMController.cpp
 *  
 *
 *  Created by Daniel Condon on 24/08/12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 */

#include "IBMController.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>

using namespace std;

const int levels = 0;
const double width = 100.0;
const double height = 100.0;

IBMController::IBMController(int nCreatures){
	srand(time(NULL));
	creatureTree = new Quadtree(0.0f, 0.0f, width, height, 0, levels);
	//terrain = 0;
	int idIncrement = 0;
	for (int i = 0; i < nCreatures; i++) {
		double a = ((double)(rand()%(int)(width*100*2))/100)-width;
		double b = ((double)(rand()%(int)(height*100*2))/100)-height;
		Brain* create = new Brain(a, b, 2.0, idIncrement);
		objs.push_back(create);
		idIncrement++;
	}
}

IBMController::~IBMController(){
	for (int i = 0; i < objs.size(); i++) {
		delete objs.at(i);
	}
	objs.erase(objs.begin(), objs.end());
	delete creatureTree;
}

int IBMController::getNumCreatures(){
	return objs.size();
}

Brain* IBMController::getCreature(int who){
	return objs.at(who);
}

void IBMController::GroupSenses(){
	for (int i = 0; i < objs.size(); i++) {
		if (objs.at(i)->getAlive()) {
			objs.at(i)->AddNearby(creatureTree->GetCreaturesNear(objs.at(i)->getPos().getX(), objs.at(i)->getPos().getY(), objs.at(i)->getRange()));
		}
	}
}
	
void IBMController::Cycle(){
	creatureTree->Clear();
	for (int i = 0; i < objs.size(); i++) {
		if (objs.at(i)->getAlive()) {
			creatureTree->AddCreature(objs.at(i));
		}
	}
	
	GroupSenses();
	for (int i = 0; i < objs.size(); i++) {
		if (objs.at(i)->getAlive()) {
			objs.at(i)->Move();
			objs.at(i)->InfectOthers();
		}
	}
}

//DEBUG
Quadtree* IBMController::getTree(){
	return creatureTree;
}
